//
//  EDNetResponse.swift
//  Project
//
//  Created by chenfanfang on 2020/10/11.
//  Copyright © 2020 chenfanfang. All rights reserved.
//

import UIKit

enum ErrorCode: String {
    /// 数据解析出问题
    case parseError = "9999"
    /// 服务端返回的数据为空
    case emptyError = "9998"
    /// 实例化AES为空
    case instanceAesError = "9997"
    /// 解密出错
    case decriptError = "9996"
    /// 解密后数据为空
    case decriptEmpty = "9995"
}

class APR_NetResponse: NSObject {
    
    let errorMessage: String?
    let errorCode: String?
    let data: [String: Any]?
    let originData: [String: Any]?
    //=================================================================
    //                           构造器
    //=================================================================
    // MARK: - 构造器
    init(errorMsg: String, errorCode: ErrorCode) {
        errorMessage = errorMsg
        self.errorCode = errorCode.rawValue
        data = nil
        originData = nil
    }
    
    init(error: Error) {
        errorMessage = error.localizedDescription
        errorCode = "\((error as NSError).code)"
        data = nil
        originData = nil
    }
    init(response: Any?) {
        if let response = response as? [String: Any] {
            if let success = response["success"] as? Bool, success == true {
                errorMessage = nil
                errorCode = nil
                data = response["payload"] as? [String: Any]
                originData = response
            } else {
                let errorDict = response["error"] as? [String: Any] ?? [String: Any]()
                errorMessage = "\(errorDict["message"] as? String ?? "")"
                errorCode = "\(errorDict["code"] as? Int ?? 0)"
                data = nil
                originData = response
            }
            
        } else {
            errorCode = ErrorCode.parseError.rawValue
            errorMessage = "数据解析出问题";
            data = nil
            originData = nil
        }
    }
}
